<template>
	<view class="box">
		<!-- 取消订单 -->
		<u-navbar title="去接乘客" placeholder @leftClick="Cancel">
		</u-navbar>
		<!-- 导航到起点 -->
		<view class="headBox">
			<view>
				<!-- 用户的出发地 -->
				<h2>
					<span class="goto">去</span><span class="userorigin">{{orderInfo.origin}}</span>
				</h2>
			</view>
			<view>
				<view class="headBox_first">
					<u-icon name="arrow-upward" color="#4D4E56" size="40"></u-icon>
				</view>
				<span>导航</span>
			</view>
		</view>
		<!-- 需要多长时间 -->
		<!-- <view class="headBox_com">
			<span>需要<text style='color: orange;font-weight: 700;'>{{minute}}</text>分内到达乘客上车点</span>
		</view> -->

		<!-- 地图 -->
		<view class="mapbox">
			<map id="navMap" class="map" enable-traffic="true" enable-scroll="true" show-location='true'
				:polyline="polyline" :markers="initialPoint"></map>
			<!-- 下雨效果 -->
			<canvas canvas-id="effect" id="effect"></canvas>
		</view>
		<!-- 信息 -->
		<view class="Information">
			<view class="userBox">
				<image src="../../static/用户.png" mode=""></image>
				<span>{{tel | telHide}}</span>
			</view>
			<view>
				<!-- 订单信息 -->
				<view class="Information_1">
					<div class='round'></div>
					<!-- 用户出发地 -->
					<text class="text">{{orderInfo.departure}}</text>
				</view>
				<view class="Information_2">
					<div class='round2'></div>
					<!-- 用户目的地 -->
					<text class="text">{{orderInfo.destination}}</text>
				</view>
			</view>
			<!-- 聊天 -->
			<view class="">
				<u-icon name="chat" color="#464749" size="35" @click="Chat"></u-icon>
			</view>
			<!-- 电话联系 -->
			<view class="">
				<u-icon name="phone-fill" color="#464749" size="35" @click="payTel(tel)"></u-icon>
			</view>
		</view>
		<!-- 底部到达目的地 -->
		<view class="but">
			<!-- 司机到达 -->
			<button v-if="finishPath" :disabled="arriveState" @tap="finishAddress">完成订单</button>
			<button v-else :disabled="arriveState" @tap="arrive">到达地点</button>
		</view>
		<!-- 提示用户取消订单---司机在路上 -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import amap from "../../common/amap-wx.130.js"
	import Particle from '@/common/effect.js'
	import {
		mapState
	} from 'vuex'

	import {
		trendsPath
	} from '@/common/utils.js'
	export default {
		data() {
			return {
				longitude: '', //经度
				latitude: '', //纬度
				amapPlugin: null, // 插件效果
				gaodeKey: "4412f1a1546136b8476c2c1011cbbad9", //  高德地图申请的key
				navMap: '', // 初始实例化地图对象
				points: [], // 缩放视野---记录起点和终点
				initialPoint: [{
					id: 0,
					latitude: '',
					longitude: '',
					iconPath: "../../static/Car.png",
					width: 40,
					height: 40
				}],
				polyline: [], //路线的规划
				distance: '', //距离
				minute: '', //分钟
				tel: '', //乘客电话
				arriveState: true, //按钮状态
				carNum: 0, //次数
				finishPath: false, //标识用户停止叫车
			}
		},
		onLoad(option) {
			this.amapPlugin = new amap.AMapWX({
				key: this.gaodeKey
			})
			// 实例化地图对象
			this.navMap = uni.createMapContext("navMap", this)

			// 雨水效果
			this.Rain = Particle.Particle
			// 获取手机大小
			uni.getSystemInfo({
				success: res => {
					this.with = res.windowWidth
					this.scale = this.with / 375
				}
			})

			this.ctx = uni.createCanvasContext('effect')
			this.height = 768 / 2 * this.scale
			this.rain = new this.Rain(this.ctx, this.with, this.height, {
				amount: 100,
				speedFactor: 0.03
			})

			console.log(this.orderInfo, '订单信息')
			console.log(this.orderInfo.city, '订单的城市')
			// 获取司机定位
			this.getPosition()
			// 电话
			this.tel = this.orderInfo.userPhone.toString()
			// 查看接单的城市 天气
			this.getWeather()

			// 收到用户取消订单的通知
			this.getmsg()
		},
		onShow() {},
		computed: {
			...mapState('driverInfo', ['orderInfo'])
		},
		methods: {
			// 收到用户取消订单的通知
			getmsg() {
				this.socket.on('cancelOrder', message => {
					clearTimeout(this.timeOut)
					this.finishPath = true
					setTimeout(() => {
						this.$refs.uToast.show({
							type: 'default',
							message: "用户取消订单",
							url: '/pages/FlashGet/FlashGet',
							iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/loading.png'
						})
					}, 2000)
				})
			},
			// 获取用户目的地
			pathPlanning() {
				// 获取用户定位的地点
				let originLatLong = JSON.parse(this.orderInfo.originLatLong)
				console.log(originLatLong, 106)

				this.points[1] = {
					longitude: originLatLong.longitude,
					latitude: originLatLong.latitude
				}
				this.initialPoint[1] = {
					id: 1,
					longitude: originLatLong.longitude,
					latitude: originLatLong.latitude,
					iconPath: "../../static/终点.png",
					width: 40,
					height: 40
				}
				console.log(this.points.length, 162)

				// 绘制路线
				if (this.points.length == 2) {
					console.log('绘制路线', 166)
					this.amapPlugin.getDrivingRoute(this.getDataObj())
					// 缩放地图
					this.navMap.includePoints({
						padding: [100],
						points: this.points
					})
				}
			},
			// 绘制路线
			getDataObj() {
				if (this.finishPath) {
					console.log('乘客取消订单')
					return
				}
				let that = this
				let color = '#00aaff'
				return {
					// 起点
					origin: that.points[0].longitude + ',' + that.points[0].latitude,
					// 终点
					destination: that.points[1].longitude + ',' + that.points[1].latitude,
					success: data => {
						console.log(data, '驾车的路线')
						that.distance = (data.paths[0].distance / 1000).toFixed(1)
						that.minute = Math.ceil(data.paths[0].duration / 60)
						// 驾车的路线
						let points = []
						if (!data || !data.paths || !data.paths[0] || !data.paths[0].steps) {
							uni.$showMsg('查询失败')
							return
						}
						let steps = data.paths[0].steps
						steps.forEach(item => {
							let polylines = item.polyline.split(';')
							polylines.forEach(item1 => {
								let locations = item1.split(',')
								points.push({
									longitude: locations[0],
									latitude: locations[1]
								})
							})
						})
						// 路线的规划
						that.polyline = [{
							points,
							color,
							width: 3
						}]


						// 模拟司机开车 接用户
						console.log(that.polyline[0].points, 214)
						console.log(that.polyline[0].points.length, 215)

						if (this.polyline[0].points.length > 9) {
							// 改变起点
							this.points[0].longitude = this.polyline[0].points[8].longitude
							this.points[0].latitude = this.polyline[0].points[8].latitude
						} else if (this.polyline[0].points.length > 2) {
							// 改变起点
							this.points[0].longitude = this.polyline[0].points[2].longitude
							this.points[0].latitude = this.polyline[0].points[2].latitude
						} else if (that.polyline[0].points.length == 2) {
							that.carNum++
							console.log(that.carNum, 230)
							// 改变起点
							that.points[0].longitude = that.polyline[0].points[1].longitude
							that.points[0].latitude = that.polyline[0].points[1].latitude
							if (that.carNum == 2) {
								that.initialPoint[0] = {
									id: 0,
									longitude: that.points[0].longitude,
									latitude: that.points[0].latitude,
									iconPath: "../../static/Car.png",
									width: 30,
									height: 30
								}
								// 按钮恢复
								that.arriveState = false
								that.carNum = 0
								console.log('司机到达目的地')
								return
							}
						}
						this.timeOut = setTimeout(() => {
							that.initialPoint[0] = {
								id: 0,
								longitude: that.points[0].longitude,
								latitude: that.points[0].latitude,
								iconPath: "../../static/Car.png",
								width: 30,
								height: 30
							}
							that.amapPlugin.getDrivingRoute(that.getDataObj())
						}, 500)
					},
					fail(err) {
						console.log('报错了', err)
					}
				}
			},
			//获取地址
			getPosition() {
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: res => {
						console.log(res, 264)
						// // 纬度
						// this.initialPoint[0].latitude = res.latitude
						// // 经度
						// this.initialPoint[0].longitude = res.longitude

						// // 设置缩放
						// this.points[0] = {
						// 	longitude: res.longitude,
						// 	latitude: res.latitude
						// }

						this.initialPoint[0].latitude = 24.504658
						this.initialPoint[0].longitude = 118.177301

						// 设置缩放
						this.points[0] = {
							longitude: 118.177301,
							latitude: 24.504658
						}

						// 获取用户定位
						this.pathPlanning()
					},
					fail(err) {
						console.log(err, '报错了')
					}
				})
			},
			//聊天
			Chat() {
				let userChat = {
					userId:this.name+'user',
					UserFace:this.driverImg,
					userName:this.driverName,
					chat:'打车'
				}
				uni.setStorageSync('userChat', userChat)
				uni.navigateTo({
					url: "/pages/chat/chat"
				})
			},
			// 到达---用户指定出发--地址
			async arrive() {
				console.log('更换地图')
				this.finishPath = true
				this.arriveState = true

				// 改变订单，数据库添加接单时间
				const result = await this.$http('/setOut', this.orderInfo, 'POST')
				console.log(result, 312)
				if (result.code !== 200) {
					uni.$showMsg('出发失败', 'error')
					return
				}

				// 通知用户，司机已到达
				this.socket.emit('updateAddress', this.orderInfo)

				// 更换路线
				this.points = []
				console.log(JSON.parse(this.orderInfo.route), 323)

				// 订单路线
				let newPath = JSON.parse(this.orderInfo.route)
				console.log(newPath, '新路线', 312)
				this.points = newPath


				this.initialPoint = []
				this.initialPoint[0] = {
					id: 0,
					longitude: this.points[0].longitude,
					latitude: this.points[0].latitude,
					iconPath: "../../static/Car.png",
					width: 40,
					height: 40
				}
				this.initialPoint[1] = {
					id: 1,
					longitude: this.points[1].longitude,
					latitude: this.points[1].latitude,
					iconPath: "../../static/终点.png",
					width: 40,
					height: 40
				}

				this.navMap.includePoints({
					padding: [100],
					points: this.points
				})

				// 封装好的
				this.amapPlugin.getDrivingRoute(trendsPath(this.points, this))
			},
			// 完成订单
			async finishAddress() {
				// 改变订单，数据库完成添加接单时间
				const result = await this.$http('/setEnd', this.orderInfo, 'POST')
				if (result.code !== 200) {
					console.log('完成失败')
					return
				}

				// 发送socket---告知用户，路程结束
				this.socket.emit('finishOrder', this.orderInfo)
				// 跳转--路程结束界面
				uni.navigateTo({
					url: '/pages/EndPath/EndPath'
				})
			},
			// 获取当前天气信息
			getWeather() {
				this.amapPlugin.getWeather({
					city: this.orderInfo.city,
					success: res => {
						console.log(res, 311)
						let weather = res.liveData.weather
						if (weather == '大雨' || weather == '小雨' || weather == '中雨' || weather == '强降雨' ||
							weather == '连续降雨') {
							// 开始下雨
							this.rain.run()
						} else {
							// 停止下雨
							this.rain.clear()
						}
					},
					fail: () => {
						uni.showToast({
							title: '没有开启位置权限',
							icon: 'none'
						})
					}
				})
			},
			//取消订单
			Cancel() {
				uni.showModal({
					title: '提示',
					content: '取消订单会降低您的服务分，您确认要取消吗?',
					cancelText: "取消", // 取消按钮的文字  
					confirmText: "确认", // 确认按钮文字 
					confirmColor: '#F54E40', //确认字体的颜色
					cancelColor: '#000', //取消字体的颜色
					success: async res => {
						if (res.confirm) {
							console.log('司机点击确定')

							// 司机取消订单
							const result = await this.$http('/cancelDriver', this.orderInfo, 'POST')
							if (result.code !== 200) return console.log('取消订单失败')
							// 通知用户订单被取消
							this.socket.emit('callUser_cancel', this.orderInfo)

							uni.showToast({
								title: '取消订单成功',
								duration: 2000,
							})
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/FlashGet/FlashGet' //跳转前往乘客地点
								})
							}, 2000)
						} else if (res.cancel) {
							console.log('司机点击取消')
						}
					}
				})
			},
			// 拨打电话
			payTel(tel) {
				uni.makePhoneCall({
					phoneNumber: tel
				})
			}
		},
	}
</script>

<style lang="scss">
	.box {
		height: 100%;
		width: 750rpx;

	}

	.headBox {
		width: 100%;
		height: 140rpx;
		display: flex;
	}

	.headBox>view:nth-child(1) {
		width: 75%;
		height: 160rpx;
		border: 1px solid #F6F6F6;
	}

	.headBox>view:nth-child(2) {
		width: 25%;
		height: 160rpx;
		border: 1px solid #F6F6F6;
		text-align: center;
	}

	.headBox_first {
		width: 50%;
		margin: 0 auto;
	}

	.headBox>view>h2 {
		padding-left: 7%;
		font-size: 20px;
		margin-top: 5%;
	}

	.userorigin {
		color: orange;
		font-size: 20px;
	}

	.goto {
		color: black;
		margin-right: 5px;
	}

	.span_first {
		padding-left: 20px;
		color: silver;
		margin-top: 5px;
	}

	.headBox_com {
		width: 100%;
		height: 100rpx;
		border: 1px solid #F6F6F6;
	}

	.headBox_com span {
		padding-left: 7%;
		line-height: 50px;
	}

	.mapbox {
		width: 100%;
		height: 600rpx;
		position: relative;
	}

	.Information {
		width: 100%;
		height: 300rpx;
		display: flex;
		margin-bottom: 5px;
	}

	.but {
		width: 100%;
	}

	.but>button {
		background-color: orange;
		color: white;
		height: 60px;
		line-height: 60px;
		font-size: 20px;
	}

	.Information img {
		height: 40px;
		width: 40px;
		border-radius: 25px;
	}

	.Information>view:nth-child(1) {
		width: 40%;
		text-align: center;
		position: relative;
	}

	.Information>view:nth-child(2) {
		width: 40%;
		position: relative;
		margin-top: 3%;
	}

	.Information>view>span {
		color: silver;
	}

	.Information>view:nth-child(3),
	.Information>view:nth-child(4) {
		width: 12%;
		position: relative;
		display: flex;
	}

	.icon {
		margin-left: 20px;
	}

	.map {
		width: 100%;
		height: 100%;
	}

	.round {
		height: 8px;
		width: 8px;
		background-color: green;
		border-radius: 25px;
		margin-top: 5px;
	}

	.round2 {
		height: 8px;
		width: 8px;
		background-color: orange;
		border-radius: 25px;
		margin-top: 5px;
	}

	.text {
		margin-left: 5px;
	}

	.Information_1 {
		display: flex;
	}

	.Information_1 text,
	.Information_2 text {
		font-size: 14px;
	}

	.Information_2 {
		display: flex;
		margin-top: 5px;
	}

	// 雨水
	#effect {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0px;
	}

	.userBox {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 47%;
			height: 47%;
		}
	}
</style>
